import { ref, watch, nextTick, computed, onMounted } from 'vue'
export default function useFixed(props) {
  const FIXED_HEIGHT = 26
  const groupsRef = ref(null)
  const groupHeights = ref([])
  const currentIndex = ref(0)
  const scrollY = ref(0)
  const distance = ref(0)

  const fixedTitle = computed(() => {
    if (scrollY.value < 0) return ''
    const currentGroup = props.data[currentIndex.value]
    return currentGroup ? currentGroup.title : ''
  })

  const fixedStyle = computed(() => {
    const distanceVal = distance.value
    const diff = (distanceVal > 0 && distanceVal < FIXED_HEIGHT) ? distanceVal - FIXED_HEIGHT : 0
    return {
      transform: `translate3d(0,${diff}px,0)`
    }
  })

  watch(scrollY, (newY) => {
    const groupHeightsVal = groupHeights.value
    for (let i = 0; i < groupHeightsVal.length - 1; i++) {
      const groupHeightTop = groupHeightsVal[i]
      const groupHeightBottom = groupHeightsVal[i + 1]
      if (newY >= groupHeightTop && newY <= groupHeightBottom) {
        currentIndex.value = i
        distance.value = groupHeightBottom - newY
        break
      }
    }
  })

  onMounted(() => {
    calculate()
  })

  watch(() => props.data, async () => {
    await nextTick()
    calculate()
  })

  function calculate() {
    if (!groupsRef.value) return
    const list = groupsRef.value.children
    const groupHeightsVal = groupHeights.value

    let height = 0
    groupHeightsVal.length = 0
    groupHeightsVal.push(height)
    for (let i = 0; i < list.length; i++) {
      height += list[i].clientHeight
      groupHeightsVal.push(height)
    }
  }

  function onScroll(pos) {
    scrollY.value = -pos.y
  }

  return {
    fixedTitle,
    groupsRef,
    fixedStyle,
    currentIndex,
    onScroll
  }
}
